<?php

// 拍卖

namespace app\shop\controller;

use think\Db;
use think\Url;
use think\Cache;
use think\Request;
use think\Session;
use think\Controller;
use app\shop\model\Member as MemberModel;
use app\shop\model\Auction as AuctionModel;
use app\shop\model\Information as InformationModel;
use app\shop\model\AuctionGoods as AuctionGoodsModel;
use app\shop\model\AuctionOrder as AuctionOrderModel;
use app\shop\model\AuctionRecord as AuctionRecordModel;
use app\shop\model\MemberAuction as MemberAuctionModel;
use app\shop\model\MemberAddress as MemberAddressModel;


class Auction extends Controller
{

    /**
     * 拍卖主页
     * @param AuctionModel $auction
     * @param AuctionGoodsModel $auctionGoods
     * @return mixed
     */
    public function index(AuctionModel $auction, AuctionGoodsModel $auctionGoods)
    {

        // 获取今天的拍卖活动
        $t = time();
        $start = mktime(0, 0, 0, date("m", $t), date("d", $t), date("Y", $t));
        $end = mktime(23, 59, 59, date("m", $t), date("d", $t), date("Y", $t));
        $con['start_time'] = ['between', [$start, $end]];

        // 拍卖活动
        $data = $auction->where($con)->field('id,end_time,status,picUrl,title,start_time')->order('create_time', 'desc')->select();
        $str = "";
        foreach ($data as &$value) {
            $str .= $value['id'] . ",";
            $value['count_down'] = gettime(time(), $value['end_time']);
        }

        // 拍卖商品
        $goods = $auctionGoods->where('auction_id', 'in', $str)->field('id,picUrl,title,auction_id,starting_price')->select();


        return $this->fetch('', [
            'mate_head' => '拍卖主页',
            'data'      => $data,
            'goods'     => $goods
        ]);
    }


    /**
     * 拍卖活动主页
     * @param Request $request
     * @param AuctionModel $auction
     * @param AuctionGoodsModel $auctionGoods
     * @return mixed
     */
    public function good_list(Request $request, AuctionModel $auction, AuctionGoodsModel $auctionGoods, AuctionRecordModel $auctionRecord)
    {

        // 获取参数
        $inquire = $request->param();
        $auction_id = $request->param('id');

        // banner图
        $banner_list = $auction->where('id', $auction_id)->field('id,picUrl,end_time,title')->find();

        // 默认排序
        $sort = ['id' => 'desc'];
        // 排序传参
        if (!empty($inquire['order'])) $sort = [$inquire['order'] => 'desc'];

        // 拍卖商品
        $goods = $auctionGoods->with('Record')->where('auction_id', $auction_id)->field('id,picUrl,title,auction_id,starting_price,deal_price')->order($sort)->select();

        // 拍卖结束时间
        $count_down = gettime(time(), $banner_list['end_time']);


        return $this->fetch('', [
            'mate_head'   => $banner_list['title'],
            'goods'       => $goods,
            'auction_id'  => $auction_id,
            'count_down'  => $count_down,
            'banner_list' => $banner_list,
        ]);
    }


    /**
     * 拍卖商品详情
     * @param Request $request
     * @param AuctionGoodsModel $auctionGoods
     * @param AuctionModel $auction
     * @param AuctionRecordModel $auctionRecord
     * @param InformationModel $information
     * @return mixed
     */
    public function good_detail(Request $request, AuctionGoodsModel $auctionGoods, AuctionModel $auction, AuctionRecordModel $auctionRecord, InformationModel $information)
    {
        // 获取参数
        $id = $request->param('id');

        // 拍卖商品详情
        $item = $auctionGoods->where('id', $id)->find();

        // 商品多图反序列化
        $item['picArr'] = (array)unserialize($item['picArr']);
        $pic_count = count($item['picArr']);

        $item['count'] = $auctionRecord->where('id', $id)->count();
        // 拍卖活动
        $data = $auction->where('id', $item['auction_id'])->find();
        $auction_total = $auctionGoods->where('auction_id', $item['auction_id'])->count();

        // 拍卖纪录
        $record = $auctionRecord->with('Member')->where('goods_id', $id)->order('id', 'desc')->paginate(10, false);

        foreach ($record as &$value) {
            $value['Member']['username'] = substr($value['Member']['username'],0,3)."****".substr($value['Member']['username'],7,4);
        }

        // 总共出价次数
        $count = $auctionRecord->where('goods_id', $id)->count();

        // 卖家承诺 保证金须知
        $information[0] = $information::get(7);
        $information[1] = $information::get(8);

        // 拍卖商品
        $auction_goods = $auctionGoods->where('auction_id', $item['auction_id'])->limit(5)->select();

        $bond = "";
        $find = (new MemberAuctionModel())->where(['member_id' => Session::get('member_id'), 'goods_id' => $item['id']])->find();
        if ($find) {
            $bond = 1;
        } else {
            $bond = 2;
        }
        $mm = 0;
        if ($data['end_time'] < time()) {
            $a = self::add_order($id);
            if ($a['code'] == 201) {
                $mm = 1;
            }

        }


        return $this->fetch('', [
            'mate_head'     => '拍卖详情',
            'item'          => $item,
            'data'          => $data,
            'bond'          => $bond,
            'record'        => $record,
            'count'         => $count,
            'pic_count'     => $pic_count,
            'information'   => $information,
            'auction_total' => $auction_total,
            'auction_goods' => $auction_goods,
            'mm'            => $mm

        ]);
    }


    public function chujia()
    {
        if (Request::instance()->isPost()) {

            $member_id = Session::get('member_id');

            $goods_id = Request::instance()->param('goods_id');

            $draw_id = Request::instance()->param('draw_id');

            $model = new AuctionRecordModel();

            if (!empty($goods_id) && !empty($member_id)) {

                $auction = new AuctionModel();
                $end_time = $auction->where('id', $draw_id)->value('end_time');
                if ($end_time < time()) {
                    return ['code' => 403, 'message' => '拍卖已结束'];
                }

                $goods = new AuctionGoodsModel();
                $data = $goods->where('id', $goods_id)->find();
                $mon = $model->where('goods_id', $goods_id)->max('bind');
                $now_mon = $model->where(['member_id' => $member_id, 'goods_id' => $goods_id])->max('bind');

                if (!empty($now_mon)) {
                    if ($mon == $now_mon) {
                        return ['code' => 202];
                    }
                }


                $now_price = '';
                if ($data['deal_price'] == 0) {
                    $now_price = $data['starting_price'] + $data['bidding'];
                } else {
                    $now_price = $data['deal_price'] + $data['bidding'];
                }


                Db::startTrans();

                try {

                    $goods->save(['deal_price' => $now_price], ['id' => $goods_id]);

                    $con = [
                        'auction_id'  => $draw_id,
                        'goods_id'    => $goods_id,
                        'member_id'   => $member_id,
                        'bind'        => $now_price,
                        'update_time' => time()
                    ];

                    $model->allowField(true)->save($con);

                    // 判断时间 延长拍卖时间

                    $now_time = time() + 300;
                    if ($end_time < $now_time) {
                        // 延长五分钟
                        $new_end_time = $end_time + 300;
                        $auction->save(['end_time' => $new_end_time], ['id' => $draw_id]);
                    }

                    Db::commit();

                    return ['code' => 200, 'price' => $now_price];

                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();

                    return ['code' => 402, 'message' => 2];

                }


            } else {
                return ['code' => 402, 'message' => 1];
            }
        }


    }


    public function add_order($goods_id)
    {

        $model = new AuctionRecordModel();
        // 如果拍卖活动已结束 获取出价最高的一条信息
        $bind = $model->where('goods_id', $goods_id)->max('bind');
        $user = $model->where(['goods_id' => $goods_id, 'bind' => $bind])->find();
        $person = (new MemberModel())->where('id', $user['member_id'])->value('nickname');
        $find = Db::name('auction_order')->where('goods_id', $goods_id)->find();
        if ($find) {

            return ['code' => 201];
        }

        // 获取低价
        $reserve_price = (new AuctionGoodsModel())->where('id', $goods_id)->value('reserve_price');

        if ($bind > $reserve_price) {
            Db::startTrans();
            $current_price = $model->where('goods_id', $goods_id)->max('bind');
            $person_member_id = $model->where(['goods_id' => $goods_id, 'bind' => $current_price])->value('member_id');
            try {
                $goods = (new AuctionGoodsModel())->where('id', $goods_id)->find();
                // 拍卖订单生成
                $ini = [
                    'member_id'      => $person_member_id,
                    'goods_id'       => $goods_id,
                    'title'          => $goods['title'],
                    'picUrl'         => $goods['picUrl'],
                    'order_number'   => self::createNumber(),
                    'price'          => $bind,
                    'address_name'   => '',
                    'address_phone'  => '',
                    'address_area'   => '',
                    'address_site'   => '',
                    'status'         => 0,
                    'way'            => '未支付',
                    'express_number' => '',
                    'express_name'   => '',
                    'express_value'  => '',
                ];

                // 生成拍卖订单
                Db::name('auction_order')->insert($ini);

                // 拍卖商品信息
                $condition = [
                    'deal_price' => $bind,
                    'deal_time'  => time(),
                    'member_id'  => $person_member_id,
                ];

                (new AuctionGoodsModel())->save($condition, ['id' => $goods_id]);

                Db::commit();

                return ['code' => 201];

            } catch (\Exception $e) {

                // 回滚事务
                Db::rollback();

                return ['code' => 404];

            }


        } else {
            return ['code' => 402];
        }

    }


    public function pay()
    {
        $oid = Request::instance()->param('oid');
        $memberId = Session::get('member_id');

        $item = (new AuctionOrderModel())->where('id', $oid)->find();

        //用户默认收货地址
        $address = (new MemberAddressModel)->where(['member_id' => Session::get('member_id'), 'status' => 1])->field('id,name,phone,address,area_info')->find();

        // 收获地址列表
        $addressList = (new MemberAddressModel())->where(['member_id' => Session::get('member_id')])->limit(3)->select()->toArray();

        // 微信回调信息 阿里回调信息
        $information_wechat = 'auction|' . $memberId . '|' . $item['order_number'];
        $information_alipy = 'auction|' . $memberId . '|' . $item['order_number'];


        return $this->fetch('', [
            'mate_head'          => '支付页面',
            'find'               => $item,
            'address'            => $address,
            'address_list'       => $addressList,
            'information_wechat' => $information_wechat,
            'information_alipy'  => $information_alipy
        ]);
    }


    /**
     * 生成订单号
     */
    protected function createNumber()
    {
        //订单号码主体（YYYYMMDDHHIISSNNNNNNNN）
        $order_id_main = date('YmdHis') . rand(10000000, 99999999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
        $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);

        return $order_id;
    }


    public function detail()
    {
        $id = Request::instance()->param('id');

        $result = (new AuctionOrderModel())->where('id', $id)->find();

        // 物流信息
        $delivery = '';
        if ($result['status'] > 1) {
            $action = self::expressView($result['express_number'], $result['express_value']);

            // 订单流程 显示的出货时间
            if ($action['code'] == 200) {

                $delivery = $action['data']['data'][0]['time'];
                $logistics = $action['data'];
            } else {
                $logistics['data'] = '';
            }
        } else {
            $logistics['data'] = '';
        }

        return $this->fetch('', [
            'mate_head' => '订单详情',
            'data'      => $result,
            'delivery'  => $delivery,
            'logistics' => $logistics,
        ]);
    }

    /**
     * 物流查询
     * @param $express_number
     * @param $express_value
     * @return array
     */
    public function expressView($express_number, $express_value)
    {

        // 修改BUG：订单详情规避空订单
        if (empty($express_value) || empty($express_number)) win('此订单错误', Url::build('MemberOrder/index'));

        // 快递100
        $data['customer'] = Cache::get('web_express_customer');
        $data['param'] = json_encode(['com' => $express_value, 'num' => $express_number]);
        $data["sign"] = strtoupper(md5($data['param'] . Cache::get('web_express_key') . $data['customer']));

        $information = $this->expressPost($data, Cache::get('web_express_url'));

        if ($information['message'] == 'ok') {

            $information['com'] = Db::name('express')->where(['code' => $information['com']])->value('name');

            return ['code' => 200, 'data' => $information];

        } else {

            return ['code' => 402];
        }

    }


    /**
     * 快递100查询
     */
    protected function expressPost($data, $url)
    {
        $o = "";
        foreach ($data as $k => $v) {
            $o .= "$k=" . urlencode($v) . "&";        //默认UTF-8编码格式
        }
        // halt($o);
        $post_data = substr($o, 0, -1);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        //value为0表示直接输出结果
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $is_success = curl_exec($ch);
        curl_close($ch);
        return json_decode($is_success, true);
    }


}